home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / perl / 5.10.0 / File / Path.pm < prev    next >
Encoding:
Perl POD Document  |  2009-06-26  |  29.4 KB  |  895 lines

  1. package File::Path;
  2.  
  3. use 5.005_04;
  4. use strict;
  5.  
  6. use Cwd 'getcwd';
  7. use File::Basename ();
  8. use File::Spec     ();
  9.  
  10. BEGIN {
  11.     if ($] < 5.006) {
  12.         # can't say 'opendir my $dh, $dirname'
  13.         # need to initialise $dh
  14.         eval "use Symbol";
  15.     }
  16. }
  17.  
  18. use Exporter ();
  19. use vars qw($VERSION @ISA @EXPORT);
  20. $VERSION = '2.04';
  21. @ISA     = qw(Exporter);
  22. @EXPORT  = qw(mkpath rmtree);
  23.  
  24. my $Is_VMS   = $^O eq 'VMS';
  25. my $Is_MacOS = $^O eq 'MacOS';
  26.  
  27. # These OSes complain if you want to remove a file that you have no
  28. # write permission to:
  29. my $Force_Writeable = grep {$^O eq $_} qw(amigaos dos epoc MSWin32 MacOS os2);
  30.  
  31. sub _carp {
  32.     require Carp;
  33.     goto &Carp::carp;
  34. }
  35.  
  36. sub _croak {
  37.     require Carp;
  38.     goto &Carp::croak;
  39. }
  40.  
  41. sub _error {
  42.     my $arg     = shift;
  43.     my $message = shift;
  44.     my $object  = shift;
  45.  
  46.     if ($arg->{error}) {
  47.         $object = '' unless defined $object;
  48.         push @{${$arg->{error}}}, {$object => "$message: $!"};
  49.     }
  50.     else {
  51.         _carp(defined($object) ? "$message for $object: $!" : "$message: $!");
  52.     }
  53. }
  54.  
  55. sub mkpath {
  56.     my $old_style = (
  57.         UNIVERSAL::isa($_[0],'ARRAY')
  58.         or (@_ == 2 and (defined $_[1] ? $_[1] =~ /\A\d+\z/ : 1))
  59.         or (@_ == 3
  60.             and (defined $_[1] ? $_[1] =~ /\A\d+\z/ : 1)
  61.             and (defined $_[2] ? $_[2] =~ /\A\d+\z/ : 1)
  62.         )
  63.     ) ? 1 : 0;
  64.  
  65.     my $arg;
  66.     my $paths;
  67.  
  68.     if ($old_style) {
  69.         my ($verbose, $mode);
  70.         ($paths, $verbose, $mode) = @_;
  71.         $paths = [$paths] unless UNIVERSAL::isa($paths,'ARRAY');
  72.         $arg->{verbose} = defined $verbose ? $verbose : 0;
  73.         $arg->{mode}    = defined $mode    ? $mode    : 0777;
  74.     }
  75.     else {
  76.         if (@_ > 0 and UNIVERSAL::isa($_[-1], 'HASH')) {
  77.             $arg = pop @_;
  78.             exists $arg->{mask} and $arg->{mode} = delete $arg->{mask};
  79.             $arg->{mode} = 0777 unless exists $arg->{mode};
  80.             ${$arg->{error}} = [] if exists $arg->{error};
  81.         }
  82.         else {
  83.             @{$arg}{qw(verbose mode)} = (0, 0777);
  84.         }
  85.         $paths = [@_];
  86.     }
  87.     return _mkpath($arg, $paths);
  88. }
  89.  
  90. sub _mkpath {
  91.     my $arg   = shift;
  92.     my $paths = shift;
  93.  
  94.     local($")=$Is_MacOS ? ":" : "/";
  95.     my(@created,$path);
  96.     foreach $path (@$paths) {
  97.         next unless length($path);
  98.         $path .= '/' if $^O eq 'os2' and $path =~ /^\w:\z/s; # feature of CRT 
  99.         # Logic wants Unix paths, so go with the flow.
  100.         if ($Is_VMS) {
  101.             next if $path eq '/';
  102.             $path = VMS::Filespec::unixify($path);
  103.         }
  104.         next if -d $path;
  105.         my $parent = File::Basename::dirname($path);
  106.         unless (-d $parent or $path eq $parent) {
  107.             push(@created,_mkpath($arg, [$parent]));
  108.         }
  109.         print "mkdir $path\n" if $arg->{verbose};
  110.         if (mkdir($path,$arg->{mode})) {
  111.             push(@created, $path);
  112.         }
  113.         else {
  114.             my $save_bang = $!;
  115.             my ($e, $e1) = ($save_bang, $^E);
  116.             $e .= "; $e1" if $e ne $e1;
  117.             # allow for another process to have created it meanwhile
  118.             if (!-d $path) {
  119.                 $! = $save_bang;
  120.                 if ($arg->{error}) {
  121.                     push @{${$arg->{error}}}, {$path => $e};
  122.                 }
  123.                 else {
  124.                     _croak("mkdir $path: $e");
  125.                 }
  126.             }
  127.         }
  128.     }
  129.     return @created;
  130. }
  131.  
  132. sub rmtree {
  133.     my $old_style = (
  134.         UNIVERSAL::isa($_[0],'ARRAY')
  135.         or (@_ == 2 and (defined $_[1] ? $_[1] =~ /\A\d+\z/ : 1))
  136.         or (@_ == 3
  137.             and (defined $_[1] ? $_[1] =~ /\A\d+\z/ : 1)
  138.             and (defined $_[2] ? $_[2] =~ /\A\d+\z/ : 1)
  139.         )
  140.     ) ? 1 : 0;
  141.  
  142.     my $arg;
  143.     my $paths;
  144.  
  145.     if ($old_style) {
  146.         my ($verbose, $safe);
  147.         ($paths, $verbose, $safe) = @_;
  148.         $arg->{verbose} = defined $verbose ? $verbose : 0;
  149.         $arg->{safe}    = defined $safe    ? $safe    : 0;
  150.  
  151.         if (defined($paths) and length($paths)) {
  152.             $paths = [$paths] unless UNIVERSAL::isa($paths,'ARRAY');
  153.         }
  154.         else {
  155.             _carp ("No root path(s) specified\n");
  156.             return 0;
  157.         }
  158.     }
  159.     else {
  160.         if (@_ > 0 and UNIVERSAL::isa($_[-1],'HASH')) {
  161.             $arg = pop @_;
  162.             ${$arg->{error}}  = [] if exists $arg->{error};
  163.             ${$arg->{result}} = [] if exists $arg->{result};
  164.         }
  165.         else {
  166.             @{$arg}{qw(verbose safe)} = (0, 0);
  167.         }
  168.         $paths = [@_];
  169.     }
  170.  
  171.     $arg->{prefix} = '';
  172.     $arg->{depth}  = 0;
  173.  
  174.     $arg->{cwd} = getcwd() or do {
  175.         _error($arg, "cannot fetch initial working directory");
  176.         return 0;
  177.     };
  178.     for ($arg->{cwd}) { /\A(.*)\Z/; $_ = $1 } # untaint
  179.  
  180.     @{$arg}{qw(device inode)} = (stat $arg->{cwd})[0,1] or do {
  181.         _error($arg, "cannot stat initial working directory", $arg->{cwd});
  182.         return 0;
  183.     };
  184.  
  185.     return _rmtree($arg, $paths);
  186. }
  187.  
  188. sub _rmtree {
  189.     my $arg   = shift;
  190.     my $paths = shift;
  191.  
  192.     my $count  = 0;
  193.     my $curdir = File::Spec->curdir();
  194.     my $updir  = File::Spec->updir();
  195.  
  196.     my (@files, $root);
  197.     ROOT_DIR:
  198.     foreach $root (@$paths) {
  199.         if ($Is_MacOS) {
  200.             $root  = ":$root" unless $root =~ /:/;
  201.             $root .= ":"      unless $root =~ /:\z/;
  202.         }
  203.         else {
  204.             $root =~ s{/\z}{};
  205.         }
  206.  
  207.         # since we chdir into each directory, it may not be obvious
  208.         # to figure out where we are if we generate a message about
  209.         # a file name. We therefore construct a semi-canonical
  210.         # filename, anchored from the directory being unlinked (as
  211.         # opposed to being truly canonical, anchored from the root (/).
  212.  
  213.         my $canon = $arg->{prefix}
  214.             ? File::Spec->catfile($arg->{prefix}, $root)
  215.             : $root
  216.         ;
  217.  
  218.         my ($ldev, $lino, $perm) = (lstat $root)[0,1,2] or next ROOT_DIR;
  219.  
  220.         if ( -d _ ) {
  221.             $root = VMS::Filespec::pathify($root) if $Is_VMS;
  222.             if (!chdir($root)) {
  223.                 # see if we can escalate privileges to get in
  224.                 # (e.g. funny protection mask such as -w- instead of rwx)
  225.                 $perm &= 07777;
  226.                 my $nperm = $perm | 0700;
  227.                 if (!($arg->{safe} or $nperm == $perm or chmod($nperm, $root))) {
  228.                     _error($arg, "cannot make child directory read-write-exec", $canon);
  229.                     next ROOT_DIR;
  230.                 }
  231.                 elsif (!chdir($root)) {
  232.                     _error($arg, "cannot chdir to child", $canon);
  233.                     next ROOT_DIR;
  234.                 }
  235.             }
  236.  
  237.             my ($device, $inode, $perm) = (stat $curdir)[0,1,2] or do {
  238.                 _error($arg, "cannot stat current working directory", $canon);
  239.                 next ROOT_DIR;
  240.             };
  241.  
  242.             ($ldev eq $device and $lino eq $inode)
  243.                 or _croak("directory $canon changed before chdir, expected dev=$ldev inode=$lino, actual dev=$device ino=$inode, aborting.");
  244.  
  245.             $perm &= 07777; # don't forget setuid, setgid, sticky bits
  246.             my $nperm = $perm | 0700;
  247.  
  248.             # notabene: 0700 is for making readable in the first place,
  249.             # it's also intended to change it to writable in case we have
  250.             # to recurse in which case we are better than rm -rf for 
  251.             # subtrees with strange permissions
  252.  
  253.             if (!($arg->{safe} or $nperm == $perm or chmod($nperm, $curdir))) {
  254.                 _error($arg, "cannot make directory read+writeable", $canon);
  255.                 $nperm = $perm;
  256.             }
  257.  
  258.             my $d;
  259.             $d = gensym() if $] < 5.006;
  260.             if (!opendir $d, $curdir) {
  261.                 _error($arg, "cannot opendir", $canon);
  262.                 @files = ();
  263.             }
  264.             else {
  265.                 no strict 'refs';
  266.                 if (!defined ${"\cTAINT"} or ${"\cTAINT"}) {
  267.                     # Blindly untaint dir names if taint mode is
  268.                     # active, or any perl < 5.006
  269.                     @files = map { /\A(.*)\z/s; $1 } readdir $d;
  270.                 }
  271.                 else {
  272.                     @files = readdir $d;
  273.                 }
  274.                 closedir $d;
  275.             }
  276.  
  277.             if ($Is_VMS) {
  278.                 # Deleting large numbers of files from VMS Files-11
  279.                 # filesystems is faster if done in reverse ASCIIbetical order.
  280.                 # include '.' to '.;' from blead patch #31775
  281.                 @files = map {$_ eq '.' ? '.;' : $_} reverse @files;
  282.                 ($root = VMS::Filespec::unixify($root)) =~ s/\.dir\z//;
  283.             }
  284.             @files = grep {$_ ne $updir and $_ ne $curdir} @files;
  285.  
  286.             if (@files) {
  287.                 # remove the contained files before the directory itself
  288.                 my $narg = {%$arg};
  289.                 @{$narg}{qw(device inode cwd prefix depth)}
  290.                     = ($device, $inode, $updir, $canon, $arg->{depth}+1);
  291.                 $count += _rmtree($narg, \@files);
  292.             }
  293.  
  294.             # restore directory permissions of required now (in case the rmdir
  295.             # below fails), while we are still in the directory and may do so
  296.             # without a race via '.'
  297.             if ($nperm != $perm and not chmod($perm, $curdir)) {
  298.                 _error($arg, "cannot reset chmod", $canon);
  299.             }
  300.  
  301.             # don't leave the client code in an unexpected directory
  302.             chdir($arg->{cwd})
  303.                 or _croak("cannot chdir to $arg->{cwd} from $canon: $!, aborting.");
  304.  
  305.             # ensure that a chdir upwards didn't take us somewhere other
  306.             # than we expected (see CVE-2002-0435)
  307.             ($device, $inode) = (stat $curdir)[0,1]
  308.                 or _croak("cannot stat prior working directory $arg->{cwd}: $!, aborting.");
  309.  
  310.             ($arg->{device} eq $device and $arg->{inode} eq $inode)
  311.                 or _croak("previous directory $arg->{cwd} changed before entering $canon, expected dev=$ldev inode=$lino, actual dev=$device ino=$inode, aborting.");
  312.  
  313.             if ($arg->{depth} or !$arg->{keep_root}) {
  314.                 if ($arg->{safe} &&
  315.                     ($Is_VMS ? !&VMS::Filespec::candelete($root) : !-w $root)) {
  316.                     print "skipped $root\n" if $arg->{verbose};
  317.                     next ROOT_DIR;
  318.                 }
  319.                 if ($Force_Writeable && !chmod $perm | 0700, $root) {
  320.                     _error($arg, "cannot make directory writeable", $canon);
  321.                 }
  322.                 print "rmdir $root\n" if $arg->{verbose};
  323.                 if (rmdir $root) {
  324.                     push @{${$arg->{result}}}, $root if $arg->{result};
  325.                     ++$count;
  326.                 }
  327.                 else {
  328.                     _error($arg, "cannot remove directory", $canon);
  329.                     if ($Force_Writeable && !chmod($perm, ($Is_VMS ? VMS::Filespec::fileify($root) : $root))
  330.                     ) {
  331.                         _error($arg, sprintf("cannot restore permissions to 0%o",$perm), $canon);
  332.                     }
  333.                 }
  334.             }
  335.         }
  336.         else {
  337.             # not a directory
  338.             $root = VMS::Filespec::vmsify("./$root")
  339.                 if $Is_VMS 
  340.                    && !File::Spec->file_name_is_absolute($root)
  341.                    && ($root !~ m/(?<!\^)[\]>]+/);  # not already in VMS syntax
  342.  
  343.             if ($arg->{safe} &&
  344.                 ($Is_VMS ? !&VMS::Filespec::candelete($root)
  345.                          : !(-l $root || -w $root)))
  346.             {
  347.                 print "skipped $root\n" if $arg->{verbose};
  348.                 next ROOT_DIR;
  349.             }
  350.  
  351.             my $nperm = $perm & 07777 | 0600;
  352.             if ($Force_Writeable && $nperm != $perm and not chmod $nperm, $root) {
  353.                 _error($arg, "cannot make file writeable", $canon);
  354.             }
  355.             print "unlink $canon\n" if $arg->{verbose};
  356.             # delete all versions under VMS
  357.             for (;;) {
  358.                 if (unlink $root) {
  359.                     push @{${$arg->{result}}}, $root if $arg->{result};
  360.                 }
  361.                 else {
  362.                     _error($arg, "cannot unlink file", $canon);
  363.                     $Force_Writeable and chmod($perm, $root) or
  364.                         _error($arg, sprintf("cannot restore permissions to 0%o",$perm), $canon);
  365.                     last;
  366.                 }
  367.                 ++$count;
  368.                 last unless $Is_VMS && lstat $root;
  369.             }
  370.         }
  371.     }
  372.  
  373.     return $count;
  374. }
  375.  
  376. 1;
  377. __END__
  378.  
  379. =head1 NAME
  380.  
  381. File::Path - Create or remove directory trees
  382.  
  383. =head1 VERSION
  384.  
  385. This document describes version 2.04 of File::Path, released
  386. 2007-11-13.
  387.  
  388. =head1 SYNOPSIS
  389.  
  390.     use File::Path;
  391.  
  392.     # modern
  393.     mkpath( 'foo/bar/baz', '/zug/zwang', {verbose => 1} );
  394.  
  395.     rmtree(
  396.         'foo/bar/baz', '/zug/zwang',
  397.         { verbose => 1, error  => \my $err_list }
  398.     );
  399.  
  400.     # traditional
  401.     mkpath(['/foo/bar/baz', 'blurfl/quux'], 1, 0711);
  402.     rmtree(['foo/bar/baz', 'blurfl/quux'], 1, 1);
  403.  
  404. =head1 DESCRIPTION
  405.  
  406. The C<mkpath> function provides a convenient way to create directories
  407. of arbitrary depth. Similarly, the C<rmtree> function provides a
  408. convenient way to delete an entire directory subtree from the
  409. filesystem, much like the Unix command C<rm -r>.
  410.  
  411. Both functions may be called in one of two ways, the traditional,
  412. compatible with code written since the dawn of time, and modern,
  413. that offers a more flexible and readable idiom. New code should use
  414. the modern interface.
  415.  
  416. =head2 FUNCTIONS
  417.  
  418. The modern way of calling C<mkpath> and C<rmtree> is with a list
  419. of directories to create, or remove, respectively, followed by an
  420. optional hash reference containing keys to control the
  421. function's behaviour.
  422.  
  423. =head3 C<mkpath>
  424.  
  425. The following keys are recognised as parameters to C<mkpath>.
  426. The function returns the list of files actually created during the
  427. call.
  428.  
  429.   my @created = mkpath(
  430.     qw(/tmp /flub /home/nobody),
  431.     {verbose => 1, mode => 0750},
  432.   );
  433.   print "created $_\n" for @created;
  434.  
  435. =over 4
  436.  
  437. =item mode
  438.  
  439. The numeric permissions mode to apply to each created directory
  440. (defaults to 0777), to be modified by the current C<umask>. If the
  441. directory already exists (and thus does not need to be created),
  442. the permissions will not be modified.
  443.  
  444. C<mask> is recognised as an alias for this parameter.
  445.  
  446. =item verbose
  447.  
  448. If present, will cause C<mkpath> to print the name of each directory
  449. as it is created. By default nothing is printed.
  450.  
  451. =item error
  452.  
  453. If present, will be interpreted as a reference to a list, and will
  454. be used to store any errors that are encountered.  See the ERROR
  455. HANDLING section for more information.
  456.  
  457. If this parameter is not used, certain error conditions may raise
  458. a fatal error that will cause the program will halt, unless trapped
  459. in an C<eval> block.
  460.  
  461. =back
  462.  
  463. =head3 C<rmtree>
  464.  
  465. =over 4
  466.  
  467. =item verbose
  468.  
  469. If present, will cause C<rmtree> to print the name of each file as
  470. it is unlinked. By default nothing is printed.
  471.  
  472. =item safe
  473.  
  474. When set to a true value, will cause C<rmtree> to skip the files
  475. for which the process lacks the required privileges needed to delete
  476. files, such as delete privileges on VMS. In other words, the code
  477. will make no attempt to alter file permissions. Thus, if the process
  478. is interrupted, no filesystem object will be left in a more
  479. permissive mode.
  480.  
  481. =item keep_root
  482.  
  483. When set to a true value, will cause all files and subdirectories
  484. to be removed, except the initially specified directories. This comes
  485. in handy when cleaning out an application's scratch directory.
  486.  
  487.   rmtree( '/tmp', {keep_root => 1} );
  488.  
  489. =item result
  490.  
  491. If present, will be interpreted as a reference to a list, and will
  492. be used to store the list of all files and directories unlinked
  493. during the call. If nothing is unlinked, a reference to an empty
  494. list is returned (rather than C<undef>).
  495.  
  496.   rmtree( '/tmp', {result => \my $list} );
  497.   print "unlinked $_\n" for @$list;
  498.  
  499. This is a useful alternative to the C<verbose> key.
  500.  
  501. =item error
  502.  
  503. If present, will be interpreted as a reference to a list,
  504. and will be used to store any errors that are encountered.
  505. See the ERROR HANDLING section for more information.
  506.  
  507. Removing things is a much more dangerous proposition than
  508. creating things. As such, there are certain conditions that
  509. C<rmtree> may encounter that are so dangerous that the only
  510. sane action left is to kill the program.
  511.  
  512. Use C<error> to trap all that is reasonable (problems with
  513. permissions and the like), and let it die if things get out
  514. of hand. This is the safest course of action.
  515.  
  516. =back
  517.  
  518. =head2 TRADITIONAL INTERFACE
  519.  
  520. The old interfaces of C<mkpath> and C<rmtree> take a reference to
  521. a list of directories (to create or remove), followed by a series
  522. of positional, numeric, modal parameters that control their behaviour.
  523.  
  524. This design made it difficult to add additional functionality, as
  525. well as posed the problem of what to do when the calling code only
  526. needs to set the last parameter. Even though the code doesn't care
  527. how the initial positional parameters are set, the programmer is
  528. forced to learn what the defaults are, and specify them.
  529.  
  530. Worse, if it turns out in the future that it would make more sense
  531. to change the default behaviour of the first parameter (for example,
  532. to avoid a security vulnerability), all existing code will remain
  533. hard-wired to the wrong defaults.
  534.  
  535. Finally, a series of numeric parameters are much less self-documenting
  536. in terms of communicating to the reader what the code is doing. Named
  537. parameters do not have this problem.
  538.  
  539. In the traditional API, C<mkpath> takes three arguments:
  540.  
  541. =over 4
  542.  
  543. =item *
  544.  
  545. The name of the path to create, or a reference to a list of paths
  546. to create,
  547.  
  548. =item *
  549.  
  550. a boolean value, which if TRUE will cause C<mkpath> to print the
  551. name of each directory as it is created (defaults to FALSE), and
  552.  
  553. =item *
  554.  
  555. the numeric mode to use when creating the directories (defaults to
  556. 0777), to be modified by the current umask.
  557.  
  558. =back
  559.  
  560. It returns a list of all directories (including intermediates, determined
  561. using the Unix '/' separator) created.  In scalar context it returns
  562. the number of directories created.
  563.  
  564. If a system error prevents a directory from being created, then the
  565. C<mkpath> function throws a fatal error with C<Carp::croak>. This error
  566. can be trapped with an C<eval> block:
  567.  
  568.   eval { mkpath($dir) };
  569.   if ($@) {
  570.     print "Couldn't create $dir: $@";
  571.   }
  572.  
  573. In the traditional API, C<rmtree> takes three arguments:
  574.  
  575. =over 4
  576.  
  577. =item *
  578.  
  579. the root of the subtree to delete, or a reference to a list of
  580. roots. All of the files and directories below each root, as well
  581. as the roots themselves, will be deleted. If you want to keep
  582. the roots themselves, you must use the modern API.
  583.  
  584. =item *
  585.  
  586. a boolean value, which if TRUE will cause C<rmtree> to print a
  587. message each time it examines a file, giving the name of the file,
  588. and indicating whether it's using C<rmdir> or C<unlink> to remove
  589. it, or that it's skipping it.  (defaults to FALSE)
  590.  
  591. =item *
  592.  
  593. a boolean value, which if TRUE will cause C<rmtree> to skip any
  594. files to which you do not have delete access (if running under VMS)
  595. or write access (if running under another OS). This will change
  596. in the future when a criterion for 'delete permission' under OSs
  597. other than VMS is settled.  (defaults to FALSE)
  598.  
  599. =back
  600.  
  601. It returns the number of files, directories and symlinks successfully
  602. deleted.  Symlinks are simply deleted and not followed.
  603.  
  604. Note also that the occurrence of errors in C<rmtree> using the
  605. traditional interface can be determined I<only> by trapping diagnostic
  606. messages using C<$SIG{__WARN__}>; it is not apparent from the return
  607. value. (The modern interface may use the C<error> parameter to
  608. record any problems encountered).
  609.  
  610. =head2 ERROR HANDLING
  611.  
  612. If C<mkpath> or C<rmtree> encounter an error, a diagnostic message
  613. will be printed to C<STDERR> via C<carp> (for non-fatal errors),
  614. or via C<croak> (for fatal errors).
  615.  
  616. If this behaviour is not desirable, the C<error> attribute may be
  617. used to hold a reference to a variable, which will be used to store
  618. the diagnostics. The result is a reference to a list of hash
  619. references. For each hash reference, the key is the name of the
  620. file, and the value is the error message (usually the contents of
  621. C<$!>). An example usage looks like:
  622.  
  623.   rmpath( 'foo/bar', 'bar/rat', {error => \my $err} );
  624.   for my $diag (@$err) {
  625.     my ($file, $message) = each %$diag;
  626.     print "problem unlinking $file: $message\n";
  627.   }
  628.  
  629. If no errors are encountered, C<$err> will point to an empty list
  630. (thus there is no need to test for C<undef>). If a general error
  631. is encountered (for instance, C<rmtree> attempts to remove a directory
  632. tree that does not exist), the diagnostic key will be empty, only
  633. the value will be set:
  634.  
  635.   rmpath( '/no/such/path', {error => \my $err} );
  636.   for my $diag (@$err) {
  637.     my ($file, $message) = each %$diag;
  638.     if ($file eq '') {
  639.       print "general error: $message\n";
  640.     }
  641.   }
  642.  
  643. =head2 NOTES
  644.  
  645. C<File::Path> blindly exports C<mkpath> and C<rmtree> into the
  646. current namespace. These days, this is considered bad style, but
  647. to change it now would break too much code. Nonetheless, you are
  648. invited to specify what it is you are expecting to use:
  649.  
  650.   use File::Path 'rmtree';
  651.  
  652. =head3 HEURISTICS
  653.  
  654. The functions detect (as far as possible) which way they are being
  655. called and will act appropriately. It is important to remember that
  656. the heuristic for detecting the old style is either the presence
  657. of an array reference, or two or three parameters total and second
  658. and third parameters are numeric. Hence...
  659.  
  660.     mkpath 486, 487, 488;
  661.  
  662. ... will not assume the modern style and create three directories, rather
  663. it will create one directory verbosely, setting the permission to
  664. 0750 (488 being the decimal equivalent of octal 750). Here, old
  665. style trumps new. It must, for backwards compatibility reasons.
  666.  
  667. If you want to ensure there is absolutely no ambiguity about which
  668. way the function will behave, make sure the first parameter is a
  669. reference to a one-element list, to force the old style interpretation:
  670.  
  671.     mkpath [486], 487, 488;
  672.  
  673. and get only one directory created. Or add a reference to an empty
  674. parameter hash, to force the new style:
  675.  
  676.     mkpath 486, 487, 488, {};
  677.  
  678. ... and hence create the three directories. If the empty hash
  679. reference seems a little strange to your eyes, or you suspect a
  680. subsequent programmer might I<helpfully> optimise it away, you
  681. can add a parameter set to a default value:
  682.  
  683.     mkpath 486, 487, 488, {verbose => 0};
  684.  
  685. =head3 SECURITY CONSIDERATIONS
  686.  
  687. There were race conditions 1.x implementations of File::Path's
  688. C<rmtree> function (although sometimes patched depending on the OS
  689. distribution or platform). The 2.0 version contains code to avoid the
  690. problem mentioned in CVE-2002-0435.
  691.  
  692. See the following pages for more information:
  693.  
  694.   http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=286905
  695.   http://www.nntp.perl.org/group/perl.perl5.porters/2005/01/msg97623.html
  696.   http://www.debian.org/security/2005/dsa-696
  697.  
  698. Additionally, unless the C<safe> parameter is set (or the
  699. third parameter in the traditional interface is TRUE), should a
  700. C<rmtree> be interrupted, files that were originally in read-only
  701. mode may now have their permissions set to a read-write (or "delete
  702. OK") mode.
  703.  
  704. =head1 DIAGNOSTICS
  705.  
  706. FATAL errors will cause the program to halt (C<croak>), since the
  707. problem is so severe that it would be dangerous to continue. (This
  708. can always be trapped with C<eval>, but it's not a good idea. Under
  709. the circumstances, dying is the best thing to do).
  710.  
  711. SEVERE errors may be trapped using the modern interface. If the
  712. they are not trapped, or the old interface is used, such an error
  713. will cause the program will halt.
  714.  
  715. All other errors may be trapped using the modern interface, otherwise
  716. they will be C<carp>ed about. Program execution will not be halted.
  717.  
  718. =over 4
  719.  
  720. =item mkdir [path]: [errmsg] (SEVERE)
  721.  
  722. C<mkpath> was unable to create the path. Probably some sort of
  723. permissions error at the point of departure, or insufficient resources
  724. (such as free inodes on Unix).
  725.  
  726. =item No root path(s) specified
  727.  
  728. C<mkpath> was not given any paths to create. This message is only
  729. emitted if the routine is called with the traditional interface.
  730. The modern interface will remain silent if given nothing to do.
  731.  
  732. =item No such file or directory
  733.  
  734. On Windows, if C<mkpath> gives you this warning, it may mean that
  735. you have exceeded your filesystem's maximum path length.
  736.  
  737. =item cannot fetch initial working directory: [errmsg]
  738.  
  739. C<rmtree> attempted to determine the initial directory by calling
  740. C<Cwd::getcwd>, but the call failed for some reason. No attempt
  741. will be made to delete anything.
  742.  
  743. =item cannot stat initial working directory: [errmsg]
  744.  
  745. C<rmtree> attempted to stat the initial directory (after having
  746. successfully obtained its name via C<getcwd>), however, the call
  747. failed for some reason. No attempt will be made to delete anything.
  748.  
  749. =item cannot chdir to [dir]: [errmsg]
  750.  
  751. C<rmtree> attempted to set the working directory in order to
  752. begin deleting the objects therein, but was unsuccessful. This is
  753. usually a permissions issue. The routine will continue to delete
  754. other things, but this directory will be left intact.
  755.  
  756. =item directory [dir] changed before chdir, expected dev=[n] inode=[n], actual dev=[n] ino=[n], aborting. (FATAL)
  757.  
  758. C<rmtree> recorded the device and inode of a directory, and then
  759. moved into it. It then performed a C<stat> on the current directory
  760. and detected that the device and inode were no longer the same. As
  761. this is at the heart of the race condition problem, the program
  762. will die at this point.
  763.  
  764. =item cannot make directory [dir] read+writeable: [errmsg]
  765.  
  766. C<rmtree> attempted to change the permissions on the current directory
  767. to ensure that subsequent unlinkings would not run into problems,
  768. but was unable to do so. The permissions remain as they were, and
  769. the program will carry on, doing the best it can.
  770.  
  771. =item cannot read [dir]: [errmsg]
  772.  
  773. C<rmtree> tried to read the contents of the directory in order
  774. to acquire the names of the directory entries to be unlinked, but
  775. was unsuccessful. This is usually a permissions issue. The
  776. program will continue, but the files in this directory will remain
  777. after the call.
  778.  
  779. =item cannot reset chmod [dir]: [errmsg]
  780.  
  781. C<rmtree>, after having deleted everything in a directory, attempted
  782. to restore its permissions to the original state but failed. The
  783. directory may wind up being left behind.
  784.  
  785. =item cannot chdir to [parent-dir] from [child-dir]: [errmsg], aborting. (FATAL)
  786.  
  787. C<rmtree>, after having deleted everything and restored the permissions
  788. of a directory, was unable to chdir back to the parent. This is usually
  789. a sign that something evil this way comes.
  790.  
  791. =item cannot stat prior working directory [dir]: [errmsg], aborting. (FATAL)
  792.  
  793. C<rmtree> was unable to stat the parent directory after have returned
  794. from the child. Since there is no way of knowing if we returned to
  795. where we think we should be (by comparing device and inode) the only
  796. way out is to C<croak>.
  797.  
  798. =item previous directory [parent-dir] changed before entering [child-dir], expected dev=[n] inode=[n], actual dev=[n] ino=[n], aborting. (FATAL)
  799.  
  800. When C<rmtree> returned from deleting files in a child directory, a
  801. check revealed that the parent directory it returned to wasn't the one
  802. it started out from. This is considered a sign of malicious activity.
  803.  
  804. =item cannot make directory [dir] writeable: [errmsg]
  805.  
  806. Just before removing a directory (after having successfully removed
  807. everything it contained), C<rmtree> attempted to set the permissions
  808. on the directory to ensure it could be removed and failed. Program
  809. execution continues, but the directory may possibly not be deleted.
  810.  
  811. =item cannot remove directory [dir]: [errmsg]
  812.  
  813. C<rmtree> attempted to remove a directory, but failed. This may because
  814. some objects that were unable to be removed remain in the directory, or
  815. a permissions issue. The directory will be left behind.
  816.  
  817. =item cannot restore permissions of [dir] to [0nnn]: [errmsg]
  818.  
  819. After having failed to remove a directory, C<rmtree> was unable to
  820. restore its permissions from a permissive state back to a possibly
  821. more restrictive setting. (Permissions given in octal).
  822.  
  823. =item cannot make file [file] writeable: [errmsg]
  824.  
  825. C<rmtree> attempted to force the permissions of a file to ensure it
  826. could be deleted, but failed to do so. It will, however, still attempt
  827. to unlink the file.
  828.  
  829. =item cannot unlink file [file]: [errmsg]
  830.  
  831. C<rmtree> failed to remove a file. Probably a permissions issue.
  832.  
  833. =item cannot restore permissions of [file] to [0nnn]: [errmsg]
  834.  
  835. After having failed to remove a file, C<rmtree> was also unable
  836. to restore the permissions on the file to a possibly less permissive
  837. setting. (Permissions given in octal).
  838.  
  839. =back
  840.  
  841. =head1 SEE ALSO
  842.  
  843. =over 4
  844.  
  845. =item *
  846.  
  847. L<File::Remove>
  848.  
  849. Allows files and directories to be moved to the Trashcan/Recycle
  850. Bin (where they may later be restored if necessary) if the operating
  851. system supports such functionality. This feature may one day be
  852. made available directly in C<File::Path>.
  853.  
  854. =item *
  855.  
  856. L<File::Find::Rule>
  857.  
  858. When removing directory trees, if you want to examine each file to
  859. decide whether to delete it (and possibly leaving large swathes
  860. alone), F<File::Find::Rule> offers a convenient and flexible approach
  861. to examining directory trees.
  862.  
  863. =back
  864.  
  865. =head1 BUGS
  866.  
  867. Please report all bugs on the RT queue:
  868.  
  869. L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=File-Path>
  870.  
  871. =head1 ACKNOWLEDGEMENTS
  872.  
  873. Paul Szabo identified the race condition originally, and Brendan
  874. O'Dea wrote an implementation for Debian that addressed the problem.
  875. That code was used as a basis for the current code. Their efforts
  876. are greatly appreciated.
  877.  
  878. =head1 AUTHORS
  879.  
  880. Tim Bunce <F<Tim.Bunce@ig.co.uk>> and Charles Bailey
  881. <F<bailey@newman.upenn.edu>>. Currently maintained by David Landgren
  882. <F<david@landgren.net>>.
  883.  
  884. =head1 COPYRIGHT
  885.  
  886. This module is copyright (C) Charles Bailey, Tim Bunce and
  887. David Landgren 1995-2007.  All rights reserved.
  888.  
  889. =head1 LICENSE
  890.  
  891. This library is free software; you can redistribute it and/or modify
  892. it under the same terms as Perl itself.
  893.  
  894. =cut
  895.